package com.example.mall_system.service.Impl;

import com.example.mall_system.common.Result;
import com.example.mall_system.entity.User;
import com.example.mall_system.mapper.UserMapper;
import com.example.mall_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

import com.example.mall_system.entity.LoginResponse;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Result<User> register(User user) {
        // 检查用户名是否已存在
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            return Result.error(400, "用户名已存在");
        }
        
        // 设置默认角色为买家
        if (user.getRole() == null) {
            user.setRole(User.ROLE_BUYER);
        }
        
        // 暂时移除密码加密，直接保存明文密码
        // user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        
        // 保存用户
        userMapper.insert(user);
        return Result.success(user);
    }
    
    @Override
    public Result<LoginResponse> login(String username, String password) {
        // 查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            return Result.error(400, "用户名或密码错误");
        }

        // 暂时移除BCrypt验证，直接比较明文密码
        if (!password.equals(user.getPassword())) {
            return Result.error(400, "用户名或密码错误");
        }

        // 返回用户信息（不包含JWT令牌）
        return Result.<LoginResponse>success(new LoginResponse(user.getId(), user.getUsername(), user.getRole(), null));
    }
    
    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
    
    // 删除原内部类 LoginResponse 的定义
}